<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="标题" prop="titile">
        <el-input
          v-model="queryParams.titile"
          placeholder="请输入标题"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:announcement:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:announcement:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:announcement:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:announcement:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="announcementList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="标题" align="center" prop="titile" />
      <el-table-column
        label="消息类型"
        align="center"
        prop="msgCategory"
        :formatter="categoryFormat"
      />
      <el-table-column label="发布人" align="center" prop="sender"/>
      <el-table-column label="优先级" align="center" prop="priority"
      :formatter="priorityFormat"
       />
      <el-table-column label="通告对象类型" align="center" prop="msgType" />
      <el-table-column label="发布状态" align="center" prop="sendStatus"
      :formatter="sendStatusFormat"
      />
      <el-table-column
        label="发布时间"
        align="center"
        prop="sendTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.sendTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="撤销时间"
        align="center"
        prop="cancelTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.cancelTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.sendStatus == 0"
            size="mini"
            type="text"
            icon="el-icon-message"
            @click="publish(scope.row)"
            >发布</el-button
          >
          <el-button
            v-else
            size="mini"
            type="text"
            icon="el-icon-document-delete"
            @click="revoke(scope.row)"
            >撤销</el-button
          >
          <el-button
            v-show="scope.row.sendStatus == 0"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:announcement:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:announcement:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改系统通告对话框 -->
    <el-dialog
      :title="title"
      center
      :visible.sync="open"
      width="800px"
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="标题" prop="titile">
              <el-input
                clearable
                v-model="form.titile"
                placeholder="请输入标题"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="消息类型" prop="msgCategory">
              <el-select
                v-model="form.msgCategory"
                placeholder="请选择消息类型"
              >
               <el-option
                  v-for="dict in msgCategoryOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="开始时间" prop="startTime">
              <el-date-picker
                clearable
                size="small"
                v-model="form.startTime"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择开始时间"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束时间" prop="endTime">
              <el-date-picker
                clearable
                size="small"
                v-model="form.endTime"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择结束时间"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="优先级" prop="priority">
              <el-select v-model="form.priority" placeholder="请输入优先级">
                <el-option
                  v-for="dict in priorityOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="通告类型" prop="msgType">
              <el-select
                v-model="form.msgType"
                placeholder="请选择通告对象类型"
                @change="msgTypeClick(form.msgType)"
              >
                <el-option label="全体用户" value="ALL" />
                <el-option label="指定用户" value="USER" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="摘要" prop="msgAbstract">
              <el-input
                clearable
                v-model="form.msgAbstract"
                type="textarea"
                placeholder="请输入内容"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-show="userId">
            <el-form-item label="指定用户" prop="userIds">
              <el-select
                multiple
                @click.native="designatedUser"
                v-model="selectedUser"
                placeholder="请选择用户"
              >
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="内容">
          <editor v-model="form.msgContent" :min-height="192" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 指定用户对话框 -->
    <el-dialog :visible.sync="openUser" width="800px">
      <el-form
        :model="queryUserParams"
        ref="queryForm"
        :inline="true"
        v-show="showSearch"
        label-width="68px"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户名称" prop="userName">
              <el-input
                v-model="queryUserParams.userName"
                placeholder="请输入用户名称"
                clearable
                size="small"
                style="width: 240px"
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号码" prop="phonenumber">
              <el-input
                v-model="queryUserParams.phonenumber"
                placeholder="请输入手机号码"
                clearable
                size="small"
                style="width: 240px"
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select
                v-model="queryUserParams.status"
                placeholder="用户状态"
                clearable
                size="small"
                style="width: 240px"
              >
                <el-option
                  v-for="dict in statusOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="handleUserQuery"
              >搜索</el-button
            >
            <el-button
              icon="el-icon-refresh"
              size="mini"
              @click="resetUserQuery"
              >重置</el-button
            >
          </el-col>
        </el-row>
      </el-form>

      <el-table
        v-loading="loading"
        :data="userList"
        @selection-change="userSelection"
      >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column
          label="用户名称"
          align="center"
          key="userName"
          prop="userName"
          v-if="columns[0].visible"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          label="部门"
          align="center"
          key="deptName"
          prop="dept.deptName"
          v-if="columns[1].visible"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          label="手机号码"
          align="center"
          key="phonenumber"
          prop="phonenumber"
          v-if="columns[2].visible"
          width="120"
        />
        <el-table-column
          label="状态"
          align="center"
          key="status"
          prop="status"
          v-if="columns[3].visible"
        >
        </el-table-column>
        <el-table-column
          label="创建时间"
          align="center"
          prop="createTime"
          v-if="columns[4].visible"
          width="160"
        >
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="userCancel">取 消</el-button>
        <el-button type="primary" @click="determine">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  listAnnouncement,
  getAnnouncement,
  delAnnouncement,
  addAnnouncement,
  updateAnnouncement,
  publishAnnouncement,
  publishButton,
  revokeAnnouncement
} from "@/views/message/js/announcement.js";
import { listUser } from "@/api/system/user";
import moment from "moment";
import store from '@/store/'

export default {
  name: "Announcement",
  data() {
    return {
      //消息类型字典
      msgCategoryOptions: [],
      //优先级字典
      priorityOptions: [],
      //发布状态字典
      sendStatusOptions: [],

      userId: false,
      openUser: false,
      loading: true,
      selectionData: {},
      designationName: {},
      designationUserId: [],
      selectedUser: [],
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 系统通告表格数据
      announcementList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 状态数据字典
      statusOptions: [],
      // 用户表格数据
      userList: null,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        titile: null,
        msgContent: null,
        startTime: null,
        endTime: null,
        sender: null,
        priority: null,
        msgCategory: null,
        msgType: null,
        sendStatus: null,
        sendTime: null,
        cancelTime: null,
        busType: null,
        busId: null,
        openType: null,
        openPage: null,
        userIds: null,
        msgAbstract: null,
      },
      // 指定用户查询参数
      queryUserParams: {
        pageNum: 1,
        pageSize: 10,
        userName: undefined,
        phonenumber: undefined,
        status: undefined,
        deptId: undefined,
      },
      // 列信息
      columns: [
        { key: 0, label: `用户名称`, visible: true },
        { key: 1, label: `部门`, visible: true },
        { key: 2, label: `手机号码`, visible: true },
        { key: 3, label: `状态`, visible: true },
        { key: 4, label: `创建时间`, visible: true },
      ],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        msgCategory: [
          {
            required: true,
            message: "消息类型不能为空",
            trigger: "blur",
          },
        ],
        priority: [
          {
            required: true,
            message: "请选择优先级",
            trigger: "blur",
          },
        ],
        msgType: [
          {
            required: true,
            message: "请选择通告对象类型",
            trigger: "blur",
          },
        ],
        endTime: [
          { required: true, message: "请选择结束时间!" },
          { validator: this.endTimeValidate },
        ],
        startTime: [
          { required: true, message: "请选择开始时间!" },
          { validator: this.startTimeValidate },
        ],
      },
    };
  },
  created() {
    this.getList();
    this.getDicts("msg_category").then(response => {
      this.msgCategoryOptions = response.data;
    });
    this.getDicts("send_status").then(response => {
      this.sendStatusOptions = response.data;
    });
    this.getDicts("sys_priority").then(response => {
      this.priorityOptions = response.data;
    });
  },
  activated(){
    this.announcementList = [];
    this.total = 0;
    this.getList();
  },
  destroyed() {
    // 销毁事件总线
    this.$eventBus.$off("update_current_position");
  },
  methods: {
     // 消息类型字典翻译
    categoryFormat(row, column) {
      return this.selectDictLabel(this.msgCategoryOptions, row.msgCategory);
    },
    // 发送状态字典翻译
    sendStatusFormat(row, column) {
      return this.selectDictLabel(this.sendStatusOptions, row.sendStatus);
    },
    // 优先级字典翻译
    priorityFormat(row, column) {
      return this.selectDictLabel(this.priorityOptions, row.priority);
    },
    /** 查询系统通告列表 */
    getList() {
      this.loading = true;
      listAnnouncement(this.queryParams).then((response) => {
        if (response.code == 200) {
          this.announcementList = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      });
    },
    /** 查询用户列表 */
    getUserList() {
      this.loading = true;
      listUser(this.addDateRange(this.queryUserParams)).then((response) => {
        if (response.code == 200) {
          this.userList = response.rows;
          this.total = response.total;
          this.loading = false;
          for (let i = 0; i < this.userList.length; i++) {
            if (this.userList[i].status == 0) {
              this.userList[i].status = "正常";
            } else if (this.userList[i].status == 1) {
              this.userList[i].status = "停用";
            }
          }
        }
      });
      this.getDicts("sys_normal_disable").then((response) => {
        if (response.code == 200) {
          this.statusOptions = response.data;
        }
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    userCancel() {
      this.openUser = false;
      this.resetQuery();
    },
    // 选择指定用户确定按钮
    determine() {
      var userIdData = [];
      for (var i = 0; i < this.selectionData.length; i++) {
        this.selectedUser.push(this.selectionData[i].userName);
        userIdData.push(this.selectionData[i].userId);
      }
      this.form.userIds = userIdData.join();
      this.openUser = false;
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        titile: null,
        msgContent: null,
        startTime: null,
        endTime: null,
        sender: null,
        priority: null,
        msgCategory: null,
        msgType: null,
        sendStatus: "0",
        sendTime: null,
        cancelTime: null,
        delFlag: null,
        busType: null,
        busId: null,
        openType: null,
        openPage: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        userIds: null,
        msgAbstract: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作(页面) */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    startTimeValidate(rule, value, callback) {
      let endTime = this.form.endTime;
      if (!value || !endTime) {
        callback();
      } else if (moment(value).isBefore(endTime)) {
        callback();
      } else {
        callback("开始时间需小于结束时间");
      }
    },
    endTimeValidate(rule, value, callback) {
      let startTime = this.form.startTime;
      if (!value || !startTime) {
        callback();
      } else if (moment(startTime).isBefore(value)) {
        callback();
      } else {
        callback("结束时间需大于开始时间");
      }
    },
    /** 搜索按钮操作(对话框) */
    handleUserQuery() {
      this.queryUserParams.pageNum = 1;
      this.getUserList();
    },
    /** 重置按钮操作(页面) */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 重置按钮操作(对话框) */
    resetUserQuery() {
      this.resetForm("queryUserForm");
      this.handleUserQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    // 指定用户对话框选中数据
    userSelection(selection) {
      this.selectionData = selection;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加系统通告";
      this.getList();
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getAnnouncement(id).then((response) => {
        if (response.code == 200) {
          this.form = response.data;
          this.open = true;
          this.title = "修改系统通告";
          console.log(this.form);
        }
      });
      this.getList();
    },
    /** 用户类型 */
    msgTypeClick(value) {
      if (value == "ALL") {
        this.userId = false;
      } else if (value == "USER") {
        this.userId = true;
      }
    },
    /** 指定用户 */
    designatedUser() {
      this.selectedUser = [];
      this.openUser = true;
      this.getUserList();
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
		  this.form.updateBy=store.getters.name;//修改人
          if (this.form.id != null) {
            updateAnnouncement(this.form).then((response) => {
              if (response.code == 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }
            });
          } else {
            addAnnouncement(this.form).then((response) => {
              if (response.code == 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm(
        '是否确认删除系统通告编号为"' + ids + '"的数据项?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return delAnnouncement(ids);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 发布按钮操作 */
    publish(row) {
      const ids = row.id || this.ids;
      publishButton(ids).then((res) => {
        if (res.code == 200) {
          console.log(res);
          this.getList();
        }
      });

      publishAnnouncement();
    },
    /** 撤销按钮操作 */
    revoke(row) {
      let id = row.id
      revokeAnnouncement(id).then((res)=>{
        if (res.code == 200) {
          this.getList();
        }
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/announcement/export",
        {
          ...this.queryParams,
        },
        `system_announcement.xlsx`
      );
    },
  },
};
</script>
